<template>
  <a-spin :spinning='confirmLoading'>
    <j-form-container :disabled='formDisabled'>
      <!-- 主表单区域 -->
      <a-form :form='form' slot='detail'>
        <a-row>
          <a-col :span='12'>
            <a-form-item label='所属月份' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-date placeholder='请选择月份' v-decorator="['salaryTime']" :trigger-change='true' style='width: 100%' />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='申请人数' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input-number v-decorator="['countNum']" placeholder='请输入申请人数' style='width: 100%' />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='代发总额' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input-number v-decorator="['salaryProcessing']" placeholder='请输入代发总额' style='width: 100%' />
            </a-form-item>
          </a-col>
          <a-col :span='24'>
            <a-form-item label='备注' :labelCol='labelCol2' :wrapperCol='wrapperCol2'>
              <h-textarea v-decorator="['remake']" :autoSize='{minRows:4}' :maxLength='500' placeholder='请输入备注' />
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model='activeKey' @change='handleChangeTabs'>
      <a-tab-pane tab='工资详情' :key='refKeys[0]' :forceRender='true'>
        <j-editable-table
          :ref='refKeys[0]'
          :loading='hfWageSalaryCountTable.loading'
          :columns='hfWageSalaryCountTable.columns'
          :dataSource='hfWageSalaryCountTable.dataSource'
          :maxHeight='300'
          :disabled=true
          :rowNumber='true'
        >
        </j-editable-table>
      </a-tab-pane>
      <a-col v-if='showFlowSubmitButton' :span='24' style='text-align: center'>
        <a-button @click='handleOk'>提 交</a-button>
      </a-col>
    </a-tabs>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { splitByNum, validateDuplicateValue } from '@/utils/util'
import { FormTypes, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'


export default {
  name: 'HfWageSalaryBpmForm',
  mixins: [JEditableTableMixin],
  components: {},

  data() {
    return {
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      confirmLoading: false,
      validatorRules: {},
      refKeys: ['hfWageSalaryCount'],
      tableKeys: ['hfWageSalaryCount'],
      activeKey: 'hfWageSalaryCount',
      //工资数据
      hfWageSalaryCountTable: {
        loading: false,
        disabled: true,
        dataSource: [],
        columns: [
          {
            title: '部门',
            key: 'auditGrade',
            width: '120px',
            type: FormTypes.select,
            dictCode: 'audit_grade'
          },
          {
            title: '姓名',
            key: 'name',
            width: '80px',
            type: FormTypes.input
          },
          {
            title: '应出勤天数',
            key: 'attendanceDay',
            width: '80px',
            type: FormTypes.input
          },
          {
            title: '实际出勤天数',
            key: 'actualAttendanceDay',
            width: '80px',
            type: FormTypes.input
          },
          {
            title: '报工天数',
            key: 'workDay',
            width: '80px',
            type: FormTypes.input
          },
          {
            title: '税前工资',
            key: 'salaryBeforeTax',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '合同工资',
            key: 'contractSalary',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '岗位工资',
            key: 'postSalary',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '岗位绩效',
            key: 'postPerformance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '保密补助',
            key: 'confidentialAssistance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '交通及通讯',
            key: 'trafficCommunication',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '全勤奖',
            key: 'attendanceBonus',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: 'BM补助',
            key: 'bmAllowance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '管理津贴',
            key: 'managementAllowance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '奖励金',
            key: 'incentivePayment',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '电脑补助',
            key: 'computerAllowance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '出差补助',
            key: 'travelAllowance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '误餐补助',
            key: 'mealGrants',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '防暑降温补助',
            key: 'heatstrokePrevention',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '冬季取暖补助',
            key: 'heatingAllowance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '独生子女补助',
            key: 'oneChildAllowance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '托儿补助',
            key: 'childcareSubsidies',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '商业保险补助',
            key: 'commercialInsuranceSubsidy',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '扣款',
            key: 'deductMoney',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '税前总计',
            width: '80px',
            key: 'beforeTotal',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '养老',
            key: 'endowmentInsurance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '失业',
            key: 'unemploymentInsurance',
            type: FormTypes.input,
            width: '80px',
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '医疗',
            key: 'medicalInsurance',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '住房公积金',
            key: 'housingProvidentFund',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '社保年检补缴',
            key: 'socialSecurityCheck',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '个税',
            key: 'payTaxes',
            type: FormTypes.input,
            width: '80px',
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '其他扣款',
            key: 'otherDeductMoney',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          },
          {
            title: '税后工资',
            key: 'payrollCredit',
            width: '80px',
            type: FormTypes.input,
            customRender: (t, item, index) => {
              return splitByNum(+t)
            }
          }
        ]
      },
      url: {
        add: '/wage/hfWageSalaryBpm/add',
        edit: '/wage/hfWageSalaryBpm/edit',
        queryById: '/wage/hfWageSalaryBpm/queryById',
        hfWageSalaryCounts: {
          list: '/wage/hfWageSalaryBpm/queryCountByMainId'
        }
      },
      fields: [
        'createBy', 'createTime', 'salaryTime', 'salaryProcessing', 'bpmStatus', 'remake', 'countNum'
      ]
      // storeData: new Map(),
    }
  },

  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  watch: {
    '$store.state.bpm.bpmSubmitStates': {
      immediate: true,
      handler(val) {
        if (val && val.edit && val.edit === '1') {
          this.handleOk().then(res => {
            if (res) {
              this.$store.commit('BPM_SUBMIT_STATES', { edit: '2' })
            }
          })
        }
      }
    }
  },
  methods: {
    handleOk() {
      const that = this
      return new Promise(((resolve, reject) => {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          let url = this.url.add, method = 'post'
          if (this.model.id) {
            url = this.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(url, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              resolve(true)
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
          // return this.request(formData)
        }).catch(e => {
          this.$store.commit('BPM_SUBMIT_STATES', {})
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      }))

    },
    addBefore() {
      this.form.resetFields()
      this.hfWageSalaryCountTable.dataSource = []
    },
    editAfter() {
      let fieldval = pick(this.model, this.fields)
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.hfWageSalaryCounts.list, params, this.hfWageSalaryCountTable)
      }
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign(this.model, values)
          console.log('表单提交数据', formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, this.fields))
    }
  }
}
</script>